package com.ilock.action;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;
import com.ilock.bean.Ilockinfo;
import com.ilock.bean.Ilockloc;
import com.ilock.bean.Ilocklog;
import com.ilock.bean.Ilockstate;
import com.ilock.bean.Iuser;
import com.ilock.bean.Own;
import com.ilock.bean.Templockop;
import com.ilock.bean.templog;
import com.ilock.service.ILockLogService;
import com.ilock.service.ILockService;
import com.ilock.service.IUserService;
import com.ilock.service.ILockLocService;
import com.ilock.service.ILockStateService;
import com.ilock.util.IGPS;

public class LogAction extends ActionSupport {
	private ILockLogService ILockLogService;
	private ILockService ILockService;
	private IUserService IUserService;
	private ILockLocService ILockLocService;
	private ILockStateService ILockStateService;
	private IGPS IGPS;
	private Map<String, Object> logMap;
	private String useremail;
	private String userpassword;
	private String locktoken;
	private double lng = -999;
	private double lat = -999;
	private int lockstate = -1;
	private double scope = 100;
	private double alertDsitance = 50;
	private String timestamp = null;
	private List<templog> loglist = null;
	
	public ILockLogService getILockLogService() {
		return ILockLogService;
	}

	public void setILockLogService(ILockLogService iLockLogService) {
		ILockLogService = iLockLogService;
	}

	public ILockService getILockService() {
		return ILockService;
	}

	public void setILockService(ILockService iLockService) {
		ILockService = iLockService;
	}

	public IUserService getIUserService() {
		return IUserService;
	}

	public void setIUserService(IUserService iUserService) {
		IUserService = iUserService;
	}

	public String getUseremail() {
		return useremail;
	}

	public void setUseremail(String useremail) {
		this.useremail = useremail;
	}

	public String getUserpassword() {
		return userpassword;
	}

	public void setUserpassword(String userpassword) {
		this.userpassword = userpassword;
	}
	
	public IGPS getIGPS() {
		return IGPS;
	}

	public void setIGPS(IGPS iGPS) {
		IGPS = iGPS;
	}

	public Map<String, Object> getLogMap() {
		return logMap;
	}

	public void setLogMap(Map<String, Object> logMap) {
		this.logMap = logMap;
	}

	public List<templog> getLoglist() {
		return loglist;
	}

	public void setLoglist(List<templog> loglist) {
		this.loglist = loglist;
	}
	
	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}
	
	public ILockLocService getILockLocService() {
		return ILockLocService;
	}

	public void setILockLocService(ILockLocService iLockLocService) {
		ILockLocService = iLockLocService;
	}

	public ILockStateService getILockStateService() {
		return ILockStateService;
	}

	public void setILockStateService(ILockStateService iLockStateService) {
		ILockStateService = iLockStateService;
	}

	public String getLocktoken() {
		return locktoken;
	}

	public void setLocktoken(String locktoken) {
		this.locktoken = locktoken;
	}

	public double getLng() {
		return lng;
	}

	public void setLng(double lng) {
		this.lng = lng;
	}

	public double getLat() {
		return lat;
	}

	public void setLat(double lat) {
		this.lat = lat;
	}

	public int getLockstate() {
		return lockstate;
	}

	public void setLockstate(int lockstate) {
		this.lockstate = lockstate;
	}

//	public String FindLogByUserId(){
//		logMap = new HashMap<String, Object>();
//		Ilockinfo templockinfo = ILockService.findLockInfoByToken(locktoken);
//		if(templockinfo!=null && date!=null && useremail!=null && userpassword!=null){
//			Iuser iuser = checkUser();
//			if(iuser!=null){
//				List logList = ILockLogService.getLockLogListByUserId(iuser.getIuserNumber(), date);
//				logMap.put("logList", logList);
//				logMap.put("state", "find log by userid success");
//			}else{
//				System.out.println("user check in error");
//				logMap.put("state", "user check in error");
//			}
//		}else{
//			System.out.println("lockinfo or date or user info incompleted");
//			logMap.put("state", "lockinfo or date or user info incompleted");
//		}
//		return "success";
//	}
	
//	public String FindLogByLockId(){
//		logMap = new HashMap<String, Object>();
//		Ilockinfo templockinfo = ILockService.findLockInfoByToken(locktoken);
//		if(templockinfo!=null && date!=null){
//			List logList = ILockLogService.getLockLogListByLockId(templockinfo.getIlockInfoNumber(), date);
//			logMap.put("logList", logList);
//			logMap.put("state", "find log by lockid success");
//		}else{
//			System.out.println("lockinfo or date incompleted");
//			logMap.put("state", "lockinfo or date incompleted");
//		}
//		return "success";
//	}
	
	public String AppAddLog(){
		List templist = new ArrayList();
		logMap = new HashMap<String, Object>();
		Iuser iuser = checkUser();
		if(iuser!=null){
			List<Own> lockIDList = ILockService.getUserLockIDList(iuser.getIuserNumber());
			if(timestamp!=null){
				for(int i=0;i<lockIDList.size();i++){	
					Own lockOwn = lockIDList.get(i);
					List tplist = ILockLogService.getLockLogListByLockId(lockOwn.getIlockInfoNumber(),Timestamp.valueOf(timestamp));
					templist.addAll(tplist);
				}
				System.out.println("log found success");
				logMap.put("state", "success");
			}else{
				System.out.println("timestamp incompleted");
				logMap.put("state", "timestamp incompleted");
			}
			logMap.put("loglist", templist);
//			Map<String,Integer> maps = new HashMap();
//			if(!loglist.isEmpty()){
//				for(int i=0;i<loglist.size();i++){
//					Ilockinfo templockinfo = ILockService.findLockInfoByToken(loglist.get(i).getLocktoken());
//					if(templockinfo!=null){
//						maps.put(templockinfo.getIlockInfoNumber().toString(),templockinfo.getIlockInfoNumber());
//					}else{
//						System.out.println("lockinfo error");
//	//					logMap.put("state", "lockinfo or date or user info incompleted");
//					}
//				}
//				//get every lock's latest log
//				for(Map.Entry<String, Integer>m:maps.entrySet()){
//					List tplist = ILockLogService.getLockLogListByLockId(m.getValue(),timestamp);
//					templist.addAll(tplist);
//				}
			if(loglist!=null){
				for(int i=0;i<loglist.size();i++){
					templog tplog = loglist.get(i);
					if(tplog.getContent()!=null && tplog.getDate()!=null && tplog.getPriority()!=-999 && tplog.getSource()!=-999 && tplog.getLocktoken()!=null){
						Ilockinfo templockinfo = ILockService.findLockInfoByToken(tplog.getLocktoken());
						if(templockinfo!=null){	
							Ilocklog templocklog = new Ilocklog();
							templocklog.setIlockInfoNumber(templockinfo.getIlockInfoNumber());
							templocklog.setContent(tplog.getContent());
							templocklog.setPriority(tplog.getPriority());
							templocklog.setSource(tplog.getSource());
							templocklog.setDate(Timestamp.valueOf(tplog.getDate()));
							templocklog.setIuserNumber(iuser.getIuserNumber());
							ILockLogService.addLockLog(templocklog);
						}else{
							System.out.println("lock token error");
							logMap.put("state", "lock token error");
						}
					}else{
						System.out.println("log elements incompleted");
						logMap.put("state", "log elements incompleted");
					}				
				}			
			}else{
				logMap.put("state", "your loglist is empty");		
			}	
		}else{
			System.out.println("user check in error");
			logMap.put("state", "user check in error");	
			
		}
		return "success";
//			}
//		}else{
//			
//		}
//		Ilockinfo templockinfo = ILockService.findLockInfoByToken(locktoken);
//		if(templockinfo!=null){
//			if(content!=null && priority!=-1 && source!=-1 && date!=null){
//				Ilocklog templocklog = new Ilocklog();
//				templocklog.setIlockInfoNumber(templockinfo.getIlockInfoNumber());
//				System.out.println(content);
//				templocklog.setContent(content);
//				templocklog.setPriority(priority);
//				templocklog.setSource(source);
//				templocklog.setDate(date);
//				if(useremail!=null && userpassword!=null){
//					Iuser iuser = checkUser();
//					if(iuser!=null){
//						templocklog.setIuserNumber(iuser.getIuserNumber());
//						ILockLogService.addLockLog(templocklog);
//						System.out.println("log record with userid done");
//						logMap.put("state", "add log success");
//					}else{
//						System.out.println("user check in error");
//						logMap.put("state", "user check in error");
//					}
//				}else{
//					ILockLogService.addLockLog(templocklog);
//					System.out.println("log record without userid done");
//					logMap.put("state", "log record without userid done");
//				}
//			}else{
//				System.out.println("log info incompleted");
//				logMap.put("state", "log info incompleted");
//			}
//		}else{
//			System.out.println("lock token error");
//			logMap.put("state", "lock token error");
//		}	
	}
	
	public String LockAddLog(){
		List templist = new ArrayList();
		logMap = new HashMap<String, Object>();
		Ilockinfo templockinfo = ILockService.findLockInfoByToken(locktoken);
//		System.out.println("token:"+locktoken);
		if(templockinfo!=null){	
			//add lock state
			if(lockstate!=-1){
				Ilockstate templockstate =ILockStateService.getLockStateById(templockinfo.getIlockInfoNumber());
				Templockop templockop = ILockService.findTempLockOp(templockinfo.getIlockInfoNumber());
				if(templockop!=null){
					if(templockop.getOperate()==lockstate){
						templockop.setIsdel(1);
						ILockService.updateTempLockOp(templockop);
						logMap.put("lockop", null);
						System.out.println("lockstate equal templockop");
					}else{
						System.out.println("lockstate and templockop different");
						logMap.put("lockop", templockop);
					}
				}else{
					System.out.println("templockop not found");
				}
				if(templockstate!=null){
					//判断是否为关锁后的第一次日志上传
					if(lockstate==0 &&templockstate.getState()==1){
						//判断是否有位置上传
						if(lng!=-999 && lat!=-999){
							//有位置信息则立即上传
							templockstate.setLastLat(lat);
							templockstate.setLastLng(lng);
							System.out.println("lockAddLog:lng or lat have data");
						}else{
							//无位置信息则上传上次位置
							Ilockloc temploc = ILockLocService.getLockLatestLocation(templockinfo.getIlockInfoNumber());
							double templngA = temploc.getIlockLocLng();
							double templatA = temploc.getIlockLocLat();
							templockstate.setLastLat(templatA);
							templockstate.setLastLng(templngA);
							System.out.println("lockAddLog:lng or lat empty");
						}
					}
					templockstate.setState(lockstate);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date dd = new Date();
					templockstate.setLastTime(Timestamp.valueOf(sdf.format(dd)));
					ILockStateService.updateLockState(templockstate);
					System.out.println("operation:lock state update done");
					logMap.put("state0", "operation:lock state update done");
//					logMap.put("state", "operation:lock state update done");
				}else{
					System.out.println("lock state error");
					logMap.put("state0", "lock state error");
				}	
			}else{
				System.out.println("lock state empty");
				logMap.put("state0", "lock state empty");
			}
			//add lock location
			if(lat!=-999 && lng!=-999){
				ILockLocService.addLockLoc(templockinfo.getIlockInfoNumber(), lng, lat);
				System.out.println("operation:add lock location done");
				logMap.put("state1", "operation:add lock location done");
				//如果锁状态为0，即闭合状态，则校验锁距离与数据库中位置超过阈值
				if(lockstate==0){
					Ilockstate templockstateA =ILockStateService.getLockStateById(templockinfo.getIlockInfoNumber());
					if(templockstateA!=null){
					double templat = templockstateA.getLastLat();
					double templng = templockstateA.getLastLng();
//					///////////////////////////////////////////////此处未做判断
					if(templat!=-999 && templng !=-999){
						double dis = IGPS.getDistance(lat, lng, templat, templng);
						//与停放位置距离超过50米则报警
						if(dis>alertDsitance){
							//通知户主
							String ownContent = "skewing_";
							Ilocklog ownLockLog = new Ilocklog();
							ownLockLog.setIlockInfoNumber(templockinfo.getIlockInfoNumber());
							ownLockLog.setPriority(4);
							ownLockLog.setSource(0);
							ownLockLog.setContent(ownContent);
							SimpleDateFormat sdfA = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Date ddA = new Date();
							String nowdate = sdfA.format(ddA);
							ownLockLog.setDate(Timestamp.valueOf(nowdate));
							ILockLogService.addLockLog(ownLockLog);
							//通知周围用户
							List<Ilockloc> nearlocklist = ILockLocService.getNearLockList(templockinfo.getIlockInfoNumber(), lng, lat, scope);
							for(int j=0;j<nearlocklist.size();j++){
								Ilockloc templockloc = nearlocklist.get(j);
								if(templockloc.getIlockInfoNumber()!=null){
									String alertContent = "alert_lat"+lat+"_lng"+lng+"_lockid"+templockinfo.getIlockInfoNumber();
									Ilocklog alertLockLog = new Ilocklog();
									alertLockLog.setIlockInfoNumber(templockloc.getIlockInfoNumber());
									alertLockLog.setPriority(4);
									alertLockLog.setSource(0);
									alertLockLog.setContent(alertContent);
									alertLockLog.setDate(Timestamp.valueOf(nowdate));
									ILockLogService.addLockLog(alertLockLog);
								}else{
									System.out.println("lockinfonumber empty");
									logMap.put("state2", "lockinfonumber empty");
								}
							}
							}else{
								System.out.println("getDistance:distance less than alertDistance");
							}
						}else{
							System.out.println("getDistance:templockstateA empty");
						}
					}else{
						System.out.println("getDistance:lat or lng empty");
					}
				}else{
					System.out.println("getDistance:lockstate is unlock");
				}
			}else{
				System.out.println("lat or lng empty");
				logMap.put("state1", "lat or lng empty");
			}
			if(loglist!=null){
				for(int i=0;i<loglist.size();i++){
					templog tplog = loglist.get(i);
					System.out.println("logaction:date."+tplog.getDate());
					if(tplog.getContent()!=null && tplog.getDate()!=null && tplog.getPriority()!=-999 && tplog.getSource()!=-999){
						Ilocklog templocklog = new Ilocklog();
						templocklog.setIlockInfoNumber(templockinfo.getIlockInfoNumber());
						templocklog.setContent(tplog.getContent());
						templocklog.setPriority(tplog.getPriority());
						templocklog.setSource(tplog.getSource());
						SimpleDateFormat sdfB = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						try {
							Date ddB = sdfB.parse(tplog.getDate());
							String tempdateB = sdfB.format(ddB);
							templocklog.setDate(Timestamp.valueOf(tplog.getDate()));
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	//						templocklog.setIuserNumber(iuser.getIuserNumber());
						ILockLogService.addLockLog(templocklog);
						//check if the lock is moved
						if(tplog.getContent().equals("moved")){
							//不提醒户主
							/*String ownContent = "alert_lat"+lat+"_lng"+lng+"_own";
							Ilocklog ownLockLog = new Ilocklog();
							ownLockLog.setIlockInfoNumber(templockinfo.getIlockInfoNumber());
							ownLockLog.setPriority(4);
							ownLockLog.setSource(0);
							ownLockLog.setContent(ownContent);
							ownLockLog.setDate(Timestamp.valueOf(tplog.getDate()));
							ILockLogService.addLockLog(ownLockLog);*/
							//如果锁没有gps信号，则使用最新的gps地理位置进行报警
							if(lng!=-999 && lat!=-999){
								System.out.println("use this time's location");
							}else{
								Ilockloc temploc = ILockLocService.getLockLatestLocation(templockinfo.getIlockInfoNumber());
								lng = temploc.getIlockLocLng();
								lat = temploc.getIlockLocLat();
								System.out.println("use database's latest location");
							}
							List<Ilockloc> nearlocklist = ILockLocService.getNearLockList(templockinfo.getIlockInfoNumber(), lng, lat, scope);
							for(int j=0;j<nearlocklist.size();j++){
								Ilockloc templockloc = nearlocklist.get(j);
								if(templockloc.getIlockInfoNumber()!=null){
									String alertContent = "alert_lat"+lat+"_lng"+lng+"_lockid"+templockinfo.getIlockInfoNumber();
									Ilocklog alertLockLog = new Ilocklog();
									alertLockLog.setIlockInfoNumber(templockloc.getIlockInfoNumber());
									alertLockLog.setPriority(4);
									alertLockLog.setSource(0);
									alertLockLog.setContent(alertContent);
									alertLockLog.setDate(Timestamp.valueOf(tplog.getDate()));
									ILockLogService.addLockLog(alertLockLog);
								}else{
									System.out.println("lockinfonumber empty");
									logMap.put("state2", "lockinfonumber empty");
								}
							}
						}else{
							System.out.println("LockAddLog:insert warning log error with imcompleted info");
							logMap.put("state2", "LockAddLog:insert warning log error with imcompleted info");
						}
						logMap.put("state", "LockAddLog:add log success");
					}else{
						System.out.println("LockAddLog:log elements incompleted");
						logMap.put("state", "LockAddLog:log elements incompleted");
					}				
				}			
			}else{
				logMap.put("state", "your loglist is empty");		
			}
		}else{
			System.out.println(locktoken);
			System.out.println("LockAddLog:lock token error");
			logMap.put("state", "LockAddLog:lock token error");
			
		}
		return "success";
	}
	
	
	public String execute(){
		
		return "success";
	}
	
	/**
	 * check user's info
	 * @return
	 */
	public Iuser checkUser(){
		Iuser iuser = null;
		iuser=IUserService.checkIn(useremail, userpassword);
		return iuser;
	}

}
